package com.huluobo.user.pages

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.UIState
import com.huluobo.lib_http.Const
import com.huluobo.user.UserIntent
import com.huluobo.user.UserViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2025/8/27.
 */

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddApprovePage(navHostController: NavHostController, vm: UserViewModel = hiltViewModel()) {
    val mmkv = MMKV.defaultMMKV()

    var name by remember {
        mutableStateOf(mmkv.decodeString(Const.PARAM_UNAME, "未登录").toString())
    }

    var role by remember {
        mutableStateOf(mmkv.decodeString(Const.PARAM_ROLE, "员工").toString())
    }

    //请假类型 请假 调休 加班
    var type by remember {
        mutableStateOf("请假")
    }

    //请假开始时间
    var startTime by remember {
        mutableStateOf(SimpleDateFormat("yyyy-MM-dd 09:00:00").format(System.currentTimeMillis()))
    }

    //请假结束时间
    var endTime by remember {
        mutableStateOf(SimpleDateFormat("yyyy-MM-dd 18:00:00").format(System.currentTimeMillis()))
    }

    //控制开始时间的弹窗
    var isStartTimeShow by remember {
        mutableStateOf(false)
    }

    //控制结束时间的弹窗
    var isEndTimeShow by remember {
        mutableStateOf(false)
    }

    //请假时长
    var hours by remember {
        mutableStateOf("")
    }

    //请假原因
    var reason by remember {
        mutableStateOf("")
    }

    var isShorProgress by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            if (name == "未登录") {
                ToastUtils.showLong("当前还未登陆,请先登录")
                navHostController.navigate(RoutePath.LOGIN)
            }
        }

        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        isShorProgress = false
                        ToastUtils.showLong("添加请假失败:${it.msg}")
                        Log.e("TagA", "添加请假失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        isShorProgress = false
                        ToastUtils.showLong("添加请假成功")
                        navHostController.popBackStack()
                    }
                }
            }
        }
    })

    if (isShorProgress) {
        BaseLoadingDialog()
    }

    Column(modifier = Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(20.dp)) {
        BaseTitle(title = "添加请假", navHostController = navHostController)

        Card(
            border = BorderStroke(1.dp, Color.LightGray),
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = Color.White
            )
        ) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(20.dp)
            ) {
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(20.dp))
                Column(Modifier.height(80.dp), verticalArrangement = Arrangement.SpaceAround) {
                    Text(text = name)
                    Text(text = role)
                }
            }
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假类型 : ")
            RadioButton(selected = type == "请假", onClick = {
                type = "请假"
            })
            Text(text = "请假")
            RadioButton(selected = type == "调休", onClick = {
                type = "调休"
            })
            Text(text = "调休")
            RadioButton(selected = type == "加班", onClick = {
                type = "加班"
            })
            Text(text = "加班")
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "开始时间 : ")
            OutlinedTextField(value = startTime, onValueChange = {}, readOnly = true, trailingIcon = {
                Icon(imageVector = Icons.Default.DateRange, contentDescription = "", Modifier.clickable {
                    isStartTimeShow = true
                })
            }, modifier = Modifier.fillMaxWidth())
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "结束时间 : ")
            OutlinedTextField(value = endTime, onValueChange = {}, readOnly = true, trailingIcon = {
                Icon(imageVector = Icons.Default.DateRange, contentDescription = "", Modifier.clickable {
                    isEndTimeShow = true
                })
            }, modifier = Modifier.fillMaxWidth())
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假时长 : ")
            OutlinedTextField(value = hours, onValueChange = {}, readOnly = true, trailingIcon = {
                Text(text = "天")
            }, modifier = Modifier.fillMaxWidth())
        }

        var isError by remember {
            mutableStateOf(false)
        }
        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假原因 : ")
            OutlinedTextField(value = reason, onValueChange = {
                if (it.length > 20) {
                    isError = true
                    ToastUtils.showLong("字数不能超过20")
                } else {
                    reason = it
                    isError = false
                }
            }, trailingIcon = {
                Text(text = "${reason.length}/20", fontSize = 11.sp)
            }, modifier = Modifier.fillMaxWidth(), isError = isError)
        }

        Button(onClick = {
            isShorProgress = true
            if (TextUtils.isEmpty(hours)) {
                ToastUtils.showLong("请选择请假时间")
                return@Button
            }

            if (TextUtils.isEmpty(reason)) {
                ToastUtils.showLong("请添加请假原因")
                return@Button
            }

            val map = mapOf(
                Const.PARAM_TYPE to type,
                Const.PARAM_START_TIME to startTime,
                Const.PARAM_END_TIME to endTime,
                Const.PARAM_HOURS to hours,
                Const.PARAM_REASON to reason
            )

            vm.sendIntent(UserIntent.AddApprove(map))

        }, modifier = Modifier.fillMaxWidth()) {
            Text(text = "提交")
        }
    }

    var startDate by remember {
        mutableStateOf(0L)
    }

    var endDate by remember {
        mutableStateOf(0L)
    }

    //日期选择器的状态
    val state = rememberDatePickerState()
    if (isStartTimeShow || isEndTimeShow) {
        DatePickerDialog(onDismissRequest = {
            isStartTimeShow = false
            isEndTimeShow = false
        }, confirmButton = {
            TextButton(onClick = {
                //state.selectedDateMillis 日期选择器选中的时间
                val time = SimpleDateFormat("yyyy-MM-dd").format(state.selectedDateMillis)
                if (isStartTimeShow) {
                    startTime = "$time 09:00:00"
                    isStartTimeShow = false
                    startDate = state.selectedDateMillis!!
                } else {
                    isEndTimeShow = false
                    if (startDate == 0L) {
                        ToastUtils.showLong("请先选择请假开始时间")
                    } else {
                        endTime = "$time 18:00:00"
                        endDate = state.selectedDateMillis!!
                        hours = (((endDate - startDate) / 1000 / 60 / 60 / 24) + 1).toString()
                    }
                }
            }) {
                Text(text = "OK")
            }
        }) {
            DatePicker(state = state)
        }
    }
}